import Vue from 'vue'
import Component from './func-notification'

const NotificationConstructor = Vue.extend(Component)

const instances = []
let seed = 1

//删除一个元素
const removeInstance = (instance) => {
  if (!instance) return
  const len = instances.length
  //找到坐标
  const index = instances.findIndex(inst => instance.id === inst.id)

  // 删除元素
  instances.splice(index, 1)

  if (len <= 1) return
  const removeHeight = instance.vm.height
  for (let i = index; i < len-1 ; i++) {
    instances[i].verticalOffset =
      // 16 是空格的高度
      parseInt(instances[i].verticalOffset) - removeHeight - 16
  }
}

const notify = (options) => {
  // 服务没有dom运行环境，直接返回
  if (Vue.prototype.$isServer) return

  const {
    autoClose,
    // ...rest 代表剩下的键值对
    ...rest
  } = options

  const instance = new NotificationConstructor({
    propsData: {
      ...rest
    },
    data: {
      autoClose: autoClose === undefined ? 3000 : autoClose
    }
  })

  const id = `notification_${seed++}`
  instance.id = id

  // $mount的返回是vm
  instance.vm = instance.$mount()

  // 把提醒放到body下面
  document.body.appendChild(instance.vm.$el)
  instance.vm.visible = true

  // 默认在右下角，出现新的往上面顶
  let verticalOffset = 0
  instances.forEach(item => {
    // 中间有16的空格
    verticalOffset += item.$el.offsetHeight + 16
  })
  verticalOffset += 16

  instance.verticalOffset = verticalOffset

  // 把新生成的instance 加进去
  instances.push(instance)

  // 执行删除节点的操作
  instance.vm.$on('closed', () => {
    removeInstance(instance)
    document.body.removeChild(instance.vm.$el)
    //dom删除掉
    instance.vm.$destroy()
  })
  instance.vm.$on('close', () => {
    instance.vm.visible = false
  })

  // 返回vm
  return instance.vm
}

export default notify
